﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.EntityClient;
using System.Linq;
using System.Web.Configuration;

namespace OpenLightGroup.Common.ApplicationServices
{
    #region Providers
    public class SqlHealthReportingProvider : HealthReportingProvider
    {
        private SqlWebEventEntities _context;
        //private SqlWebEventDataClassesDataContext _context;

        /// <summary>
        /// Gets the exceptions.
        /// </summary>
        /// <param name="pageIndex">Index of the page.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns></returns>
        public override IEnumerable<HealthReportingEntryMetaData> GetExceptions(int pageIndex, int pageSize)
        {
            DateTime firstDay = DateTime.Now - TimeSpan.FromDays(7);

            var initialList = (from e in this._context.aspnet_WebEvent_Events
                               where e.ExceptionType != string.Empty
                               && e.EventTime > firstDay
                               orderby e.EventTime descending
                               select e);

            return Paginator(initialList, pageIndex, pageSize);
        }

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            this.ConnectionStringName = config["connectionStringName"];

            ConnectionStringSettings connStringConfig = WebConfigurationManager.ConnectionStrings[this.ConnectionStringName];

            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder =
                new EntityConnectionStringBuilder();

            //Set the provider name.
            entityBuilder.Provider = connStringConfig.ProviderName ?? "System.Data.SqlClient";

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = connStringConfig.ConnectionString;

            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/SqlWebEventDataModel.csdl|res://*/SqlWebEventDataModel.ssdl|res://*/SqlWebEventDataModel.msl";            

            try
            {
              
            }
            catch (Exception ex)
            {
                EventLogger.LogError(ex);
                
            }




            this._context = new SqlWebEventEntities(entityBuilder.ConnectionString);

            //this._context = new SqlWebEventDataClassesDataContext(WebConfigurationManager.ConnectionStrings[this.ConnectionStringName].ConnectionString);
        }

        public string ConnectionStringName { get; set; }

        private static IEnumerable<HealthReportingEntryMetaData> Paginator(IOrderedQueryable<aspnet_WebEvent_Events> initialList, int pageIndex, int pageSize)
        {
            var results = initialList;

            if (pageIndex > 0)
            {
                results = results.Skip(pageIndex * pageSize).OrderByDescending(e => e.EventTime);
            }

            if (pageSize > 0)
            {
                results = results.Take(pageSize).OrderByDescending(e => e.EventTime);
            }

            var x = results.Select(e => new HealthReportingEntryMetaData()
                                                               {
                                                                   ApplicationVirtualPath = e.ApplicationVirtualPath,
                                                                   EventCode = e.EventCode,
                                                                   EventDetailCode = e.EventDetailCode,
                                                                   EventId = e.EventId,
                                                                   EventTime = e.EventTime,
                                                                   EventType = e.EventType,
                                                                   Message = e.Message,
                                                                   ExceptionType = e.ExceptionType
                                                               });

            return x;
        }

        /// <summary>
        /// Gets the events by date.
        /// </summary>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <param name="pageIndex">Index of the page.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns></returns>
        public override IEnumerable<HealthReportingEntryMetaData> GetEventsByDate(DateTime startDate, DateTime endDate, int pageIndex, int pageSize)
        {
            if (endDate > startDate)
                throw new ArgumentException("endDate must be after startDate");

            var initialList = (from e in this._context.aspnet_WebEvent_Events
                               where e.EventTime >= startDate && e.EventTime <= endDate
                               orderby e.EventTime descending
                               select e);

            return Paginator(initialList, pageIndex, pageSize);
        }

        /// <summary>
        /// Gets the type of the events by.
        /// </summary>
        /// <param name="eventTypeName">Name of the event type.</param>
        /// <param name="pageIndex">Index of the page.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns></returns>
        public override IEnumerable<HealthReportingEntryMetaData> GetEventsByType(string eventTypeName, int pageIndex, int pageSize)
        {
            var initialList = (from e in this._context.aspnet_WebEvent_Events
                               where e.EventType == eventTypeName
                               orderby e.EventTime descending
                               select e);

            return Paginator(initialList, pageIndex, pageSize);
        }

        /// <summary>
        /// Gets the events.
        /// </summary>
        /// <param name="pageIndex">Index of the page.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns></returns>
        public override IEnumerable<HealthReportingEntryMetaData> GetEvents(int pageIndex, int pageSize)
        {
            var initialList = (from e in this._context.aspnet_WebEvent_Events
                               orderby e.EventTime descending
                               select e);

            return Paginator(initialList, pageIndex, pageSize);
        }

        /// <summary>
        /// Gets the event details.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public override HealthReportingEntry GetEventDetails(string id)
        {
            var output = from e in this._context.aspnet_WebEvent_Events
                         where e.EventId == id
                         select new HealthReportingEntry()
                         {
                             ApplicationPath = e.ApplicationPath,
                             ApplicationVirtualPath = e.ApplicationVirtualPath,
                             Details = e.Details,
                             EventCode = e.EventCode,
                             EventDetailCode = e.EventDetailCode,
                             EventId = e.EventId,
                             EventOccurrence = e.EventOccurrence,
                             EventSequence = e.EventSequence,
                             EventTime = e.EventTime,
                             EventType = e.EventType,
                             ExceptionType = e.ExceptionType,
                             MachineName = e.MachineName,
                             Message = e.Message,
                             RequestUrl = e.RequestUrl
                         };

            return output.FirstOrDefault();
        }
    }
    #endregion
}